<template>
  <a-modal
    :title="title"
    :width="modalWidth"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form"  :model="model" :rules="validatorRules">

        <a-form-model-item prop="phone">
          <a-input v-model="model.phone" size="large" placeholder="11 位手机号">
            <a-select slot="addonBefore" size="large" defaultValue="+86">
              <a-select-option value="+86">+86</a-select-option>
              <a-select-option value="+87">+87</a-select-option>
            </a-select>
          </a-input>
        </a-form-model-item>

        <a-row :gutter="16">
          <a-col class="gutter-row" :span="16">
            <a-form-model-item prop="captcha">
              <a-input v-model="model.captcha" size="large" type="text" placeholder="验证码"  >
                <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-button
              class="getCaptcha"
              size="large"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
              v-text="(!state.smsSendBtn && '获取验证码') || state.time + ' s'"
            ></a-button>
          </a-col>
        </a-row>

      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>

import { postAction, putAction } from '@/api/manage'
import { checkOnlyUser } from '@api/api'

  export default {
    name: "UserPhone",
    data () {
      return {
        model: {},
        title:"修改手机号",
        modalWidth:800,
        visible: false,
        confirmLoading: false,
        state: {
          time: 60,
          smsSendBtn: false,
          passwordLevel: 0,
          passwordLevelChecked: false,
          percent: 10,
          progressColor: '#FF0000'
        },
        validatorRules:{
          phone: [
            { required: true  ,message: '请输入11位手机号!',},
            { validator: this.handlePhoneCheck }
          ],
          captcha: [
            { required: true, message: '请输入验证码!', },
            { validator: this.handleCaptchaCheck }
          ]
        },
        confirmDirty:false,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        form:this.$form.createForm(this),
        url: "sys/user/changePhone",
        username:"",
      }
    },
    methods: {
      show(uname){
        if(!uname){
          this.$message.warning("当前系统无登录用户!");
          return
        }else{
          this.username = uname
          this.model = {}
          this.visible = true;
        }
      },
      handleCancel () {
        this.close()
      },
      close () {
        this.$emit('close');
        this.visible = false;
        this.disableSubmit = false;
        this.selectedRole = [];
      },
      handleOk () {

        const that = this;
        // 触发表单验证

        this.$refs['form'].validate((success) => {
          if (success) {
            that.confirmLoading = true;
            console.log("修改密码提交数据",{phone:this.model.phone,captcha:this.model.captcha})
            putAction(this.url,{phone:this.model.phone,captcha:this.model.captcha}).then((res)=>{
              if(res.success){
                console.log(res)
                that.$message.success(res.message);
                that.close();
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },

      handleConfirmBlur  (e) {
        const value = e.target.value
        this.confirmDirty = this.confirmDirty || !!value
      },

      getCaptcha(e) {
        e.preventDefault()
        let that = this
        this.$refs['form'].validateField(['phone'], (err) => {
            if (!err) {
              this.state.smsSendBtn = true;
              let interval = window.setInterval(() => {
                if (that.state.time-- <= 0) {
                  that.state.time = 60;
                  that.state.smsSendBtn = false;
                  window.clearInterval(interval);
                }
              }, 1000);
              const hide = this.$message.loading('验证码发送中..', 3);
              const params = {
                mobile: this.model.phone,
                smsmode: "3"
              };
              postAction("/sys/sms", params).then((res) => {
                if (!res.success) {
                  this.registerFailed(res.message);
                  setTimeout(hide, 0);
                }
                setTimeout(hide, 500);
              }).catch(err => {
                setTimeout(hide, 1);
                clearInterval(interval);
                that.state.time = 60;
                that.state.smsSendBtn = false;
                this.requestFailed(err);
              });
            }
          }
        );
      },
      handlePhoneCheck(rule, value, callback) {
        var reg = /^1[3456789]\d{9}$/
        if (!reg.test(value)) {
          callback(new Error("请输入正确手机号"))
        } else {
          var params = {
            phone: value,
          };
          checkOnlyUser(params).then((res) => {
            if (res.success) {
              callback()
            } else {
              callback("手机号已存在!")
            }
          })
        }
      },
      requestFailed(err) {
        this.$notification['error']({
          message: '错误',
          description: ((err.response || {}).data || {}).message || "请求出现错误，请稍后再试",
          duration: 4,
        });
        this.registerBtn = false;
      },
      handleCaptchaCheck(rule, value, callback) {
        if (!value) {
          callback(new Error("请输入验证码"))
        } else {
          callback();
        }
      },

    }
  }
</script>

<style scoped>

</style>

